package framework.web;

import framework.pojo.Item;
import framework.pojo.Page;
import framework.pojo.Record;
import framework.pojo.User;
import framework.service.ItemService;
import framework.service.RecordService;
import framework.service.impl.ItemServiceImp;
import framework.service.impl.RecordServiceImp;
import framework.utils.WebUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class ItemServlet extends BaseServlet {

    private ItemService itemService = new ItemServiceImp();

    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1 获取请求的参数 pageNo 和 pageSize 和jump
        int jump = WebUtils.parseInt(req.getParameter("jump"), 0);
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        //2 调用BookService.page(pageNo，pageSize)：Page对象
        Page<Item> page = itemService.page(pageNo, pageSize);

        page.setUrl("sale/ItemServlet?action=page");


        //3 保存Page对象到Request域中
        req.setAttribute("page", page);
        //4 请求转发

        req.getRequestDispatcher("/page/sale/item_manager.jsp").forward(req, resp);


    }

    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String img_path;
        if (ServletFileUpload.isMultipartContent((javax.servlet.http.HttpServletRequest) req)) {
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            Map<String, String> map = new LinkedHashMap<String, String>();
            ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory);
            try {
                List<FileItem> list = fileUpload.parseRequest((javax.servlet.http.HttpServletRequest) req);
                for (FileItem fileItem : list) {
                    if (fileItem.isFormField()) {
                        map.put(fileItem.getFieldName(), fileItem.getString("UTF-8"));
                    } else {
                        if (list.get(6).getString("UTF-8") == null || "".equals(list.get(6).getString("UTF-8"))) {
                            img_path = "static/img/default.jpg";

                        } else {
                            img_path = "static/img/" + list.get(2).getString("UTF-8") + ".jpg";
                            String contextPath = req.getSession().getServletContext().getRealPath("/");
                            fileItem.write(new File(contextPath + "static/img/" + list.get(2).getString("UTF-8") + ".jpg"));
                        }
                        map.put("imgPath", img_path);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            //封装为Item对象
            Item item = WebUtils.copyParamToBean(map, new Item());

            //保存商品
            itemService.addItem(item);
            resp.sendRedirect(req.getContextPath() + "/sale/ItemServlet?action=page&pageNo=" + req.getParameter("pageNo") + "&jump=1");

        }
    }

    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1、获取请求的参数id
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
//        2、删除商品
        itemService.deleteItemById(id);
//        3、重定向回商品列表管理页面
        resp.sendRedirect(req.getContextPath() + "/sale/ItemServlet?action=page&pageNo=" + req.getParameter("pageNo"));
    }

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String img_path;
        if (ServletFileUpload.isMultipartContent((javax.servlet.http.HttpServletRequest) req)) {
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            Map<String, String> map = new LinkedHashMap<String, String>();
            ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory);
            try {
                List<FileItem> list = fileUpload.parseRequest((javax.servlet.http.HttpServletRequest) req);
                for (FileItem fileItem : list) {
                    if (fileItem.isFormField()) {
                        if (fileItem.getFieldName().equals("img_path"))
                            continue;
                        map.put(fileItem.getFieldName(), fileItem.getString("UTF-8"));
                    } else {
                        if (list.get(6).getString("UTF-8") == null) {
                            img_path = list.get(7).getString("UTF-8");

                        } else {
                            img_path = "static/img/" + list.get(2).getString("UTF-8") + ".jpg";
                            String contextPath = req.getSession().getServletContext().getRealPath("/");
                            File file = new File(contextPath + "static/img/" + list.get(2).getString("UTF-8") + ".jpg");
                            fileItem.write(file);

                        }
                        map.put("imgPath", img_path);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
//        1、获取请求的参数==封装成为商品对象
            Item item = WebUtils.copyParamToBean(map, new Item());
//        2、修改商品
            itemService.updateItem(item);
//        3、重定向回商品列表管理页面
            resp.sendRedirect(req.getContextPath() + "/sale/ItemServlet?action=page&pageNo=" + req.getParameter("pageNo"));
        } else {
            System.out.println("修改商品失败");
        }
    }

    protected void getItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1 获取请求的商品编号
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        //2 查询商品
        Item item = itemService.queryItemById(id);
        //3 保存商品到Request域中
        req.setAttribute("item", item);
        //4 请求转发
        req.getRequestDispatcher("/page/sale/additem.jsp").forward(req, resp);
    }

    protected void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1 通过ItemService查询全部商品
        List<Item> items = itemService.queryItems();
        //2 把全部商品保存到Request域中
        req.setAttribute("items", items);
        //3、请求转发
        req.getRequestDispatcher("/page/sale/item_manager.jsp").forward(req, resp);
    }

    protected void GetItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取当前用户的id，根据用户所点击的商品的id，获取相应的商品对象，存储到request域中。
        //调用historyService提供的方法，添加一条浏览记录到数据库中。然后返回商品信息页
        Integer gid = WebUtils.parseInt(req.getParameter("id"), 0);

        Item item = itemService.queryItemById(gid);
        req.setAttribute("item", item);

        RecordService recordService = new RecordServiceImp();
        User u = (User) req.getSession().getAttribute("user");
        if (u != null) {
            Record entry = new Record(u.getId(), gid, item.getName(), false);
            recordService.AddRecord(entry);

        }

        req.getRequestDispatcher("/CartServlet?action=addItem&id=" + req.getParameter("id")).forward(req, resp);
    }
}
